package com.dzsw.thread;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author sunz
 * @version 1.0
 * @CreateTime 2021-04-20-16:10
 */
public class CFutureMain3 {

    public static void main(String[] args) throws Exception {
        anyOf();


    }

    public static void allOf() throws Exception {
        List<String> list = Arrays.asList("aaa", "bbb", "ccc");
        List<CompletableFuture<String>> futureList = new ArrayList<>();
        list.forEach(s -> {
            CompletableFuture<String> cf = CompletableFuture.supplyAsync(()->{
                // TODO something...
                try {
                    Thread.sleep(3 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return s + " --- " + Math.random() * 30;
            });
            futureList.add(cf);
        });
        CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0])).join();
        for (CompletableFuture<String> cf : futureList) {
            String ss = cf.join();
            System.out.println(ss);
        }
    }

    public static void anyOf() throws Exception {
        List<String> list = Arrays.asList("aaa", "bbb", "ccc");
        List<CompletableFuture<String>> futureList = new ArrayList<>();
        list.forEach(s -> {
            CompletableFuture<String> cf = CompletableFuture.supplyAsync(()->{
                // TODO something...
                try {
                    Thread.sleep(3 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return s + " --- " + Math.random() * 30;
            });
            futureList.add(cf);
        });
        CompletableFuture.anyOf(futureList.toArray(new CompletableFuture[0])).join();
        for (CompletableFuture<String> cf : futureList) {
            String ss = cf.join();
            System.out.println(ss);
        }
    }
}
